﻿using System;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Collections.Generic;
using TaskManager.Common;
using System.Data.SqlClient;
using DBUtility;
using System.Data.Odbc;
using MySQL;
using Tools;
using System.Collections;
using System.Text.RegularExpressions;


namespace TaskManager.WebTask
{
    public class ManagePL 
    {
        private OdbcConnection CnMySQL = new OdbcConnection("driver={mysql odbc 5.1 driver};database=laob;server=127.0.0.1;uid=root;pwd=;Stmt=Set Names 'GBK'");
        private string ConnectionString = "SERVER=(local);DATABASE=erp;INTEGRATED SECURITY=True;User ID=sa;Password=;";
        //private List<PingLunInfo> AllPingLun = new List<PingLunInfo>();  
        private List<string> PingLun30 = new List<string>();
        private List<string> PingLun37 = new List<string>();
        private List<string> PingLun38 = new List<string>();
        private List<string> PingLun39 = new List<string>();
        private List<string> PingLun40 = new List<string>();
        private List<string> PingLun41 = new List<string>();
        private List<string> PingLun42 = new List<string>();

        private Hashtable ht = new Hashtable();


        public void UpdateContent()
        {
            //ReadContent();
            //ReadSQL();
            //AddGoodsBrief();
            //UpdatePLtime();
            //UpdateLink();    
            //GetLinks();
            UpdateAllLinks();
            //UpdateId();
        
        }


        private void UpdateAllLinks()
        {
            RegexOptions option = (RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
            string FileName = @"D:\py\xampp\laob\zbys\index.htm";
            string FileNamenew = @"D:\py\xampp\laob\zbys\index.html";
            FileStream myStream = File.Open(FileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("gb2312"));

            string sContent = sr.ReadToEnd();
            sr.Close();
            myStream.Close();

            string sTemp = sContent;
            sContent = sContent.Replace("http://www.99qqw.net", "");
            sContent = sContent.Replace("http://x.99jk.com", "");
            sContent = sContent.Replace("gb2312", "utf-8");
            sTemp = sTemp.Replace("\"","") ;
            string regex = @"href=(?<LINK>.*).htm\s?target=_blank>";
            string field = @"LINK";
            List<string> sLinks = RegTools.GetSubList(sTemp, regex, field, option);
            CnMySQL.Open();

            foreach (string link in sLinks)
            {
                string sTempLink = link + ".htm";
                sTempLink = sTempLink.Replace("http://www.99qqw.net", "");

                regex = @"/(?<ID>\d{1,4}).htm";
                field = @"ID";
                string sOriID = RegTools.GetContentByReg(sTempLink, regex,field);

                string strSQL = " select  goods_id from ecs_goods where extension_code='" + sTempLink + "'";
                OdbcDataReader odbcdr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
                int ID = 0;
                
                while (odbcdr.Read())
                {
                    ID = odbcdr.GetInt32(0);
                }
                if (ID >0)
                {
                    sContent = sContent.Replace(sTempLink, "/goods.php?id=" + ID.ToString());
                    sContent = sContent.Replace("/crBasket/Basket.asp?PID=" + sOriID, "javascript:addToCart(" + ID.ToString() + ")");
                }
                
            }
            CnMySQL.Close();

            myStream = File.Open(FileNamenew, FileMode.Create, FileAccess.Write, FileShare.Write);
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("utf-8"));
            sw.Write(sContent);

            sw.Close();
            myStream.Close();      
            

        }

        private void UpdateId()
        {
            string strSQL = "select f20_a017,f1_a017  "
                            + " from A_017,a_016,a_015 where F2_A017=oid_a016 and f2_a016=oid_a015  and  f2_a015=0 and  f3_a015=0"
                            + " order by oid_a015 ,f1_a016,f1_a017";

            SqlConnection myConnection = new SqlConnection(ConnectionString);
            SqlCommand myCommand = new SqlCommand(strSQL, myConnection);
            myConnection.Open();
            SqlDataReader sdr = myCommand.ExecuteReader();
            CnMySQL.Open();

            string sUpdateSQL = "";
            while (sdr.Read())
            {
                sUpdateSQL = " update ecs_goods set extension_code='/Xqw/ProInfo/" + sdr.GetInt32(0) + ".htm' where  goods_name='" + sdr.GetString(1) + "'; ";
                int t = clsMySQL.ExecuteNonQuery(CnMySQL, sUpdateSQL);
            }
            sdr.Close();
            myConnection.Close();

            
            CnMySQL.Close();

        
        }

        private void GetLinks()
        {
            RegexOptions option = (RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
            string FileName = Application.StartupPath + "\\评论\\links.txt";
            FileStream myStream = File.Open(FileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8"));

            string sContent = sr.ReadToEnd();
            sr.Close();
            myStream.Close();

            string regex = @"/Product.(?<ID>.{0,5}).aspx";
            string field = @"ID";
            List<string> sPingLun = RegTools.GetSubList(sContent, regex, field, option);
            string stemp = "";
            foreach (string sID in sPingLun)
            {
                stemp += "\n" + "http://www.aizhigu.com/Product."+sID+".aspx";
            }
            stemp = stemp + "";
        
        }

        private void UpdateLink()
        {
            string FileName = Application.StartupPath + "\\评论\\cat_product.lbi";
            FileStream myStream = File.Open(FileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8"));

            string sContent = sr.ReadToEnd();
            sr.Close();
            myStream.Close();


            FileName = Application.StartupPath + "\\评论\\20100518.txt";
            myStream = File.Open(FileName, FileMode.Open, FileAccess.Read);
            sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("gb2312"));


            string aLine = "";
            
            while ((aLine = sr.ReadLine()) != null)
            {
                string[] sComp = aLine.Split('>');
                if (sComp.Length >= 4)
                {
                    sContent = sContent.Replace("/Xqw/ProInfo/" + sComp[3] + ".htm", "/goods.php?id=" + sComp[2]);
                }
            }
            
            sr.Close();
            myStream.Close();        
        
        }

        public void UpdatePLtime()
        {
            try
            {
                Random u = new Random(unchecked((int)DateTime.Now.Ticks));
                CnMySQL.Open();
                string strSQL = " select  comment_id from ecs_comment where user_name<>'admin' order by  comment_id";
                OdbcDataReader odbcdr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
                while (odbcdr.Read())
                {
                    string sID = odbcdr.GetInt32(0).ToString();
                    int click = u.Next(0, 300 * 24 * 3600);
                    DateTime dt = DateTime.Today.AddSeconds(1 - click);

                    string sSql = " update ecs_comment set add_time=UNIX_TIMESTAMP('" + dt.ToString() + "') where comment_id=" + sID;
                    int t = clsMySQL.ExecuteNonQuery(CnMySQL, sSql);
                }


                CnMySQL.Close();
            }
            catch (Exception e)
            {
                CnMySQL.Close();
            }

        }



        private void ReadSQL()
        {
            List<string> lSQL = new List<string>();
            string FileName = Application.StartupPath + "\\评论\\p.sql";
            FileStream myStream = File.Open(FileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string aLine = "";
            CnMySQL.Open();
            while ((aLine = sr.ReadLine()) != null)
            {
                aLine = aLine.Replace("_pro_introduce`", " insert into temp (t1,t2,t3,t4,t5,t6,t7,t8,t9)  ");
                //lSQL.Add(aLine);
                int tt = clsMySQL.ExecuteNonQuery(CnMySQL, aLine);
            }
            CnMySQL.Close();
            sr.Close();
            myStream.Close();        
        }

        private void ReadContent()
        {
            string FileName = Application.StartupPath + "\\评论\\p1.txt";
            FileStream myStream = File.Open(FileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string aLine = "";
            CnMySQL.Open();

            while ((aLine = sr.ReadLine()) != null)
            {
                string[] sPl = aLine.Split('|');
                if (sPl.Length > 1)
                {
                    string sSQL = "update temp set t10='" + sPl[1].Trim() + "' where t2='" + sPl[0].Trim() + "'";
                    int tt = clsMySQL.ExecuteNonQuery(CnMySQL, sSQL);
                }
            }
            CnMySQL.Close();

            sr.Close();
            myStream.Close();
            return;

            FileName = Application.StartupPath + "\\评论\\p2.txt";
            myStream = File.Open(FileName, FileMode.Open, FileAccess.Read);
            sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            aLine = "";
            while ((aLine = sr.ReadLine()) != null)
            {
                string[] sPl = aLine.Split('|');
                if (sPl.Length > 1)
                {
                    string sKey = sPl[0].Trim();
                    sKey = sKey.Replace("\'","");

                    if (ht.ContainsKey(sKey))
                    {
                        string sValue = ht[sKey].ToString();
                        sValue += "|";
                        string sTemp = sPl[1].Trim();
                        sTemp = sTemp.Replace("\'","");
                        sTemp = sTemp.Replace("\t","");
                        if (sTemp != "")
                        {
                            sValue += sTemp;
                        }

                        ht.Remove(sKey);
                        ht.Add(sKey,sValue);
                    }
                }
            }
            sr.Close();
            myStream.Close();



            
        }


        public void AddGoodsBrief()
        {
            try
            {
                CnMySQL.Open();
                string strSQL = " select  goods_id,goods_desc from ecs_goods  where goods_brief='' "
                                + " order by goods_id";
                OdbcDataReader odbcdr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
                while (odbcdr.Read())
                {
                    string sID = odbcdr.GetInt32(0).ToString();
                    string sDesc = odbcdr.GetString(1);
                    string sBrief = CleanBrief(sDesc);
                    string sSql = " update ecs_goods set goods_brief='" + sBrief + "' where goods_id=" + sID ;
                    int t = clsMySQL.ExecuteNonQuery(CnMySQL, sSql);
                }


                CnMySQL.Close();
            }
            catch (Exception e)
            {
                CnMySQL.Close();
            }        
        
        }

        private string CleanBrief(string sSource)
        {
            string sResult = Tools.RegTools.RemoveHtmlTag(sSource);
            sResult = sResult.Replace("\n", "");
            sResult = sResult.Replace("\r", "");
            sResult = sResult.Replace("&nbsp;", "");
            sResult = sResult.Replace("本页内容仅供成年人浏览，18周岁以下人士请浏览其它页面！", "");
            sResult = sResult.Replace("[产品简介]：", "");
            sResult = sResult.Replace("★产品包含：", "");
            sResult = sResult.Replace("★套装包含：", "");
            sResult = sResult.Replace("★款式介绍：", "");
            
            sResult = sResult.Replace(" ", "");
            sResult = sResult.Replace("商品简介", "");
            //sResult = sResult.Substring(0, 40);
            return sResult;
        }


        public void AddGoodsPl()
        {
            try
            {
                CnMySQL.Open();
                ReadPL();
                string strSQL = " select parent_id as pid, ecs_goods.cat_id as tid,goods_id as gid from ecs_goods  "
                                +" left join ecs_category on ecs_goods.cat_id=ecs_category.cat_id  "
                                +" order by parent_id";
                OdbcDataReader odbcdr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
                while (odbcdr.Read())
                {
                    int PID = odbcdr.GetInt32(0);
                    int CID = odbcdr.GetInt32(1);
                    int GID = odbcdr.GetInt32(2);
                    if (PID == 0) PID = 42;
                    switch (PID.ToString())
                    {
                        case "37":
                            AddPingLun(PingLun37,GID);
                            break;
                        case "38":
                            AddPingLun(PingLun38, GID);
                            break;
                        case "39":
                            AddPingLun(PingLun39, GID);
                            break;
                        case "40":
                            AddPingLun(PingLun40, GID);
                            break;
                        case "41":
                            AddPingLun(PingLun41, GID);
                            break;
                        case "42":
                            AddPingLun(PingLun42, GID);
                            break;
                    }
                    
                }


                CnMySQL.Close();
            }
            catch (Exception e)
            {
                CnMySQL.Close();
            }
        }


        private int ReadPL()
        {
            string FileName = Application.StartupPath + "\\评论\\20100415.txt";
            FileStream myStream = File.Open(FileName, FileMode.Open, FileAccess.Read );
            StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string aLine = "";
            while ((aLine = sr.ReadLine()) != null)
            {
                string[] sPl = aLine.Split('$');
                if(sPl.Length>1)
                {
                    string sID = sPl[0].Trim();
                    switch (sID)
                    {
                        case "30":
                            PingLun30.Add(sPl[1]);
                            break;
                        case "37":
                            PingLun37.Add(sPl[1]);
                            break;
                        case "38":
                            PingLun38.Add(sPl[1]);
                            break;
                        case "39":
                            PingLun39.Add(sPl[1]);
                            break;
                        case "40":
                            PingLun40.Add(sPl[1]);
                            break;
                        case "41":
                            PingLun41.Add(sPl[1]);
                            break;
                        case "42":
                            PingLun42.Add(sPl[1]);
                            break;
                    }
                }
            }
            sr.Close();
            myStream.Close();
            return 1;
        }


        private int GetGoodsId(string sGoodsName)
        {
            string strSQL = " SELECT goods_id from ecs_goods where goods_name='" + sGoodsName + "'; ";
            OdbcDataReader odr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
            int gid = 0;
            while (odr.Read())
            {
                gid = odr.GetInt32(0);
                //break;
            }
            return gid;
        }


        private void AddPingLun(List<string> sPingLun, int GID)
        {
            int icount = 0;
            int PlCount = sPingLun.Count;
            int allcount = System.Math.Min(PlCount, 60);
            bool isAll = false;
            if (allcount < 60)
            {
                isAll = true;
            }
            int index = 0;
            Random u = new Random(unchecked((int)DateTime.Now.Ticks));
            while(icount<allcount)
            {
                if (isAll)
                {
                    index = icount;
                }
                else
                {
                    index = u.Next(0, PlCount - 1); 
                }

                string sLine = sPingLun[index];
                string[] sPL = sLine.Split('|');
                if (sPL.Length > 0)
                {
                    int click = u.Next(0, 300 * 24 * 3600);
                    int comment_rank = 4 + (click % 2);
                    DateTime dt = DateTime.Today.AddSeconds(1 - click);
                    string userpl = Filter(sPL[0]);
                    string strSQL = " insert into ecs_comment (comment_type,id_value,email,user_name,content,comment_rank,add_time,ip_address,status,parent_id) "
                      + " values (0," + GID.ToString() + ",'guest@99xfg.com','','" + userpl + "'," + comment_rank.ToString() + ", "
                      + " UNIX_TIMESTAMP('" + dt.ToString() + "'),'219.238.134.69',1,0); ";

                    int result = clsMySQL.ExecuteNonQuery(CnMySQL, strSQL);

                    if (sPL.Length>1)
                    {
                        string sReplay = Filter(sPL[1]);
                        if (sReplay != "")
                        {
                            strSQL = " SELECT last_insert_id() as tid FROM ecs_comment   ;";
                            OdbcDataReader odbcdr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
                            int commment_id = 0;
                            while (odbcdr.Read())
                            {
                                commment_id = odbcdr.GetInt32(0);
                                if (commment_id > 0)
                                {
                                    break;
                                }
                            }
                            strSQL = " insert into ecs_comment (comment_type,id_value,email,user_name,content,comment_rank,add_time,ip_address,status,parent_id) "
                              + " values (0," + GID.ToString() + ",'guest@99xfg.com','admin','" + sReplay + "',0, "
                              + " UNIX_TIMESTAMP('" + dt.ToString() + "'),'219.238.134.69',1," + commment_id.ToString() + "); ";
                            result = clsMySQL.ExecuteNonQuery(CnMySQL, strSQL);
                        
                        }

                    }
                }
                icount++;

            }
        }

        private string Filter(string sSource)
        {
            string result = sSource.Trim();
            return result.Replace("\"", "");
        }

        private int GetCategoryId(string sCatName)
        {
            string strSQL = " SELECT cat_id from ecs_category where cat_name='" + sCatName + "'; ";
            OdbcDataReader odr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
            int cid = 0;
            while (odr.Read())
            {
                cid = odr.GetInt32(0);
                //break;
            }
            if (cid == 0)
            {
                strSQL = " insert into ecs_category (cat_name,parent_id,sort_order,is_show,grade) values ('" + sCatName + "',0,1,1,0) ";
                odr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
                strSQL = " SELECT last_insert_id() as tid FROM ecs_category   ;";
                odr = clsMySQL.ExecuteReader(CnMySQL, strSQL);
                while (odr.Read())
                {
                    cid = odr.GetInt32(0);
                    if (cid > 0)
                    {
                        break;
                    }
                }
            }
            return cid;
        }
    }


    public class PingLunInfo
    {
        public string sID = "";
        public List<string> lPingLun= new List<string>();
    }
}
